package db

import (
	"fmt"
	"github.com/sirupsen/logrus"
	"gorm.io/driver/mysql"
	"gorm.io/driver/postgres"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"hcy-go/global/structs/enum"
	"hcy-go/lib/config"
	"hcy-go/lib/utils"
	"os"
	"path"
)

var db *gorm.DB

func GetDB() *gorm.DB {
	return db
}

func InitDB() {
	var logMode logger.Interface
	// 只有当日志级别时debug时才打印sql，
	if config.Conf.ShowSqlLog {
		logMode = logger.Default.LogMode(logger.Info)
	} else {
		logMode = logger.Default.LogMode(logger.Silent)
	}
	var err error
	switch config.Conf.DB {
	case enum.DBSupportType.Sqlite:
		if !utils.IsFolderExist(path.Dir(config.Conf.Sqlite.Sources[0])) {
			err = os.MkdirAll(path.Dir(config.Conf.Sqlite.Sources[0]), 0777)
			if err != nil {
				panic(err)
			}
		}
		fmt.Println(config.Conf.Sqlite.Sources[0])
		db, err = gorm.Open(sqlite.Open(config.Conf.Sqlite.Sources[0]), &gorm.Config{
			Logger: logMode,
		})
	case enum.DBSupportType.Mysql:
		db, err = gorm.Open(mysql.Open(config.Conf.MySql.Sources[0]), &gorm.Config{
			Logger: logMode,
			// SkipDefaultTransaction: true, // 跳过事务控制
			//CreateBatchSize: 500, //创建数据时每一批数据的大小
		})
	case enum.DBSupportType.Pgsql:
		db, err = gorm.Open(postgres.Open(config.Conf.PgSql.Sources[0]), &gorm.Config{
			Logger: logMode,
			// SkipDefaultTransaction: true, // 跳过事务控制
			//CreateBatchSize: 500, //创建数据时每一批数据的大小
		})
	default:
		logrus.Panic("未定义的数据库类型")
	}
	if err != nil {
		panic(fmt.Errorf("连接数据库异常: %v", err.Error()))
	}
}
